package com.atguigu.day03;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CallableDemo
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-09-08 18:51
 * @Version 1.0
 */

/**
 * callable获取多线程:相比于runnable
 * 会抛异常,有返回值,方法不同
 */
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*new Thread(() -> {
            System.out.println("----come in runable---");

        },"t1").start();
        TimeUnit.SECONDS.sleep(2);
        System.out.println(Thread.currentThread().getName() + "\t task over");*/

        FutureTask<String> futureTask = new FutureTask<>(() -> {
            System.out.println("----come in callable---");

            return "hello callable";
        });
        new Thread(futureTask,"t1").start();
        new Thread(futureTask,"t2").start();//取值只取一次,怎么好意思上课时间让人间给你跑几次去楼下买水?
        //主线程不停,可以将比较耗时的工作交给FutureTask,完成工作后在通知主线程获取结果

        TimeUnit.SECONDS.sleep(2);
        System.out.println(Thread.currentThread().getName() + "\t task over");
        System.out.println(futureTask.get());
        System.out.println(futureTask.get());


        /*FutureTask<String> futureTask = new FutureTask<>(() -> {
            System.out.println("----come in callable---");
            return "hello callable";
        });
        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            System.out.println("----come in callable---");
            return "hello callable";
        });
        new Thread(futureTask,"t1").start();
        new Thread(futureTask2,"t2").start();

        System.out.println(Thread.currentThread().getName() + "\t task over");
        System.out.println(futureTask.get());
        System.out.println(futureTask2.get());*/
    }
}
